<?php
namespace App\Listeners;

use App\Events\In\CashBillingFinished;
use App\Models\GiftLessonAcceptance;
use App\Models\StudentFirstBillingTime;
use App\Models\GiftLessonStudent;
use Carbon\Carbon;

class OnCashBillingFinished
{
    public function handle(CashBillingFinished $event)
    {
        // 记录首次购买时间
        $studentId = $event->studentId;
        $paidAt = Carbon::createFromTimestamp($event->paidAt);

        $firstBillingTime = StudentFirstBillingTime::find($studentId);
        if (empty($firstBillingTime)) {
            $firstBillingTime = new StudentFirstBillingTime();
            $firstBillingTime->setStudentId($event->studentId);
            $firstBillingTime->setBillingType(StudentFirstBillingTime::BILLING_TYPE_CASH);
            $firstBillingTime->setProductId($event->rechargeLevelId);
            $firstBillingTime->setBillId($event->billId);
            $firstBillingTime->setBillingTime($paidAt);
            $firstBillingTime->save();
        }

        $acceptances = GiftLessonAcceptance::where('student_id', $event->studentId)
            ->where('status', GiftLessonAcceptance::STATUS_ACCEPTED)
            ->get();

        if (!empty($acceptances)) {
            foreach ($acceptances as $acceptance) {
                $acceptance->giftReference($event->billId, $paidAt);
            }
        }

        if ($event->cashAmount >= 3500) {
            $student = GiftLessonStudent::find($event->studentId);
            if (empty($student)) {
                $student = new GiftLessonStudent();
                $student->setStudentId($event->studentId);
                $student->setStatus(GiftLessonStudent::STATUS_UNLOCK);
                $student->save();
            }
        }

    }
}